import { MyVue } from "@/common/MyVue";
import { CacheKeys } from "@/constant/CacheKeys";
import Constant, { GenerateResult, TopBar } from "@/constant/Constants";
import PostInfo from "@/model/PostInfo";
import { UserInfo } from "@/model/UserInfo";
import { PostRequest } from "@/protocol/request/PostRequest";
import Paging, { PagingOperate } from "@/protocol/request/Paging";
import { PostService } from "@/service/PostService";
import { UserService } from "@/service/UserService";
import DateUtil from "@/utils/DateUtil";
import LoggerUtil from "@/utils/LoggerUtil";
import UniUtil, { VideoAdOptions } from "@/utils/UniUtil";
import Util from "@/utils/Util";
import BatchDownloadUtil from "@/utils/BatchDownloadUtil";
import { Component, Hook, Setup } from "vue-facing-decorator";
@Component
export default class Post extends MyVue {
    user = new UserInfo.UserData();
    flowList = new Array<UserInfo.SimpleUser>();
    postList = new Array<PostInfo>();
    postMap = new Map<number, PostInfo>();
    cdnHost = Constant.cdnHost;
    screenWidth: string = "";
    mediaHeight: string = "320px";
    visible: boolean = false;
    refresherTriggered: boolean = false;
    currentScrollTop: number = 0;
    scrollToPosition: number = 0;
    scrollIntoView: string = ""; // 用于scroll-into-view定位
    showContent: boolean = true; // 控制内容是否显示，避免定位时闪烁
    initialLoadCompleted: boolean = false; // 标记初始加载是否完成
    currentIndex: number = 0; // 当前显示的swiper索引
    targetIndex: number = 0; // 目标帖子的索引
    isLoading: boolean = false; // 是否正在加载新数据
    touchStartTime: number = 0; // 触摸开始时间
    touchDirection: string = ""; // 触摸方向
    // 添加一个标记，表示是否需要定位到目标帖子
    needLocateTarget: boolean = false;
    request: PostRequest.QueryList = new PostRequest.QueryList();
    observer: UniNamespace.IntersectionObserver | null = null;

    // 调试用：监控当前显示帖子的状态
    get currentPost() {
        if (this.currentIndex >= 0 && this.currentIndex < this.postList.length) {
            const post = this.postList[this.currentIndex];
            LoggerUtil.info("当前帖子状态: id={}, postCurrent={}, urls.length={}",
                post?.id, post?.postCurrent, post?.urls?.length);
            return post;
        }
        return null;
    }
    async onLoad() {
        uni.setNavigationBarTitle({ title: TopBar.POST });

        uni.getSystemInfo({
            success: (res) => {
                this.screenWidth = res.screenWidth + "px";
                this.mediaHeight = res.screenWidth * 1.25 + "px";
            },
        });

        let params = Util.getPageParams();
        if (params) {
            LoggerUtil.info("获取到参数:{}", JSON.stringify(params));
            this.request.uid = params.uid;
            this.user.uid = params.uid;
            UserService.cacheRefUid();
            this.request.postId = Number(params.postId); // 目标帖子ID
            this.request.lnkId = Number(params.lnkId) || 0; // 目标帖子ID（如果是收藏或喜欢）
            this.request.type = Number(params.type) || 0; // 数据类型（0: 默认，1: 收藏，2: 喜欢）
            // 如果有目标帖子ID，先隐藏内容避免闪烁
            if (this.request.postId > 0) {
                this.showContent = false;
                this.needLocateTarget = true;
            }

            // 显示加载提示（使用页面内的加载提示，不使用uni.showLoading）
            // uni.showLoading({
            //     title: "加载中...",
            //     mask: true,
            // });

            try {
                await this.load();
            } finally {
                // 不需要隐藏加载提示，因为使用页面内的加载状态
                // uni.hideLoading();
            }
        }
    }
    async load() {
        this.postList.length = 0;
        this.flowList.length = 0;
        this.request.pageIndex = 1;

        try {
            // 如果是首次加载且有目标帖子ID，加载目标帖子前后的数据
            if (!this.initialLoadCompleted && this.request.postId > 0) {
                await this.loadInitialDataAroundTarget();

                // 在数据加载完成后，立即设置正确的索引
                const targetIndex = this.postList.findIndex(
                    (post) => post.id === this.request.postId
                );

                if (targetIndex !== -1) {
                    this.currentIndex = targetIndex;
                    this.targetIndex = targetIndex;
                    LoggerUtil.info("预设目标索引: {}", targetIndex);
                } else {
                    this.currentIndex = 0;
                    LoggerUtil.warn("未找到目标帖子，设置为0: {}", this.request.postId);
                }
            } else {
                // 普通加载
                let postList = await (<any>PostService.queryUserList(this.request));
                Util.copyList(this.postList, postList, PostInfo);
                this.currentIndex = 0; // 普通加载从第一个开始
            }

            // 加载用户信息
            let user = await UserService.getPublicData(this.user);
            Util.copy(this.user, user);

            // 更新postMap，并确保每个帖子的 postCurrent 初始化
            this.postMap.clear();
            this.postList.forEach((element) => {
                // 确保 postCurrent 有正确的初始值
                if (element.postCurrent === undefined || element.postCurrent === null) {
                    element.postCurrent = 0;
                }
                this.postMap.set(element.id, element);
            });

            // 显示内容
            LoggerUtil.info("准备显示内容，currentIndex: {}, postList.length: {}", this.currentIndex, this.postList.length);
            this.showContent = true;
            this.initialLoadCompleted = true;

            LoggerUtil.info("加载完成，共{}条数据", this.postList.length);
        } catch (error) {
            LoggerUtil.error("加载数据失败", error);

            // 如果加载失败，也要显示内容（即使是空的）
            this.showContent = true;
            this.initialLoadCompleted = true;

            // 如果加载失败，显示错误提示
            uni.showToast({
                title: "加载失败，请重试",
                icon: "none",
                duration: 2000,
            });
        }
    }

    changeMedia(e: any) {
        let id = parseInt(e.currentTarget.dataset.id);
        const post = this.postMap.get(id);
        if (post) {
            const newCurrent = e.detail.current;
            const oldCurrent = post.postCurrent;
            LoggerUtil.info("媒体切换：postId: {}, 从索引 {} 切换到 {}", id, oldCurrent, newCurrent);

            // 找到数组中的对应项
            const postIndex = this.postList.findIndex(p => p.id === id);
            if (postIndex !== -1) {
                // 使用 Vue 的响应式设置方法
                this.$set(this.postList[postIndex], 'postCurrent', newCurrent);

                // 同时更新 Map 中的数据
                post.postCurrent = newCurrent;

                LoggerUtil.info("成功更新postCurrent: postId={}, index={}, newCurrent={}", id, postIndex, newCurrent);
            } else {
                LoggerUtil.error("在postList中未找到postId为{}的帖子", id);
            }
        } else {
            LoggerUtil.error("changeMedia: 在postMap中未找到postId为{}的帖子", id);
        }
    }




    async onRefresherRefresh() {
        // 下拉刷新功能，可以保留但需要适配swiper
        LoggerUtil.info("onRefresherRefresh");
        await this.loadMoreOnSwipeDown();
    }

    onScroll(e: any) {
        this.currentScrollTop = e.detail.scrollTop;
    }

    // Swiper事件处理
    onSwiperChange(e: any) {
        const newIndex = e.detail.current;
        const oldIndex = this.currentIndex;

        LoggerUtil.info("Swiper切换：从 {} 到 {}", oldIndex, newIndex);

        this.currentIndex = newIndex;

        // 检查是否需要加载更多数据
        if (newIndex >= this.postList.length - 2) {
            // 接近底部，上滑加载更多数据
            this.loadMoreOnSwipeUp();
        } else if (newIndex <= 1) {
            // 接近顶部，下滑加载更多数据
            this.loadMoreOnSwipeDown();
        }
    }

    onTouchStart(e: any) {
        this.touchStartTime = Date.now();
        LoggerUtil.info("Touch开始");
    }

    onTouchEnd(e: any) {
        const touchEndTime = Date.now();
        const duration = touchEndTime - this.touchStartTime;
        LoggerUtil.info("Touch结束，持续时间: {}ms", duration);
    }

    // 下滑加载更多数据（在顶部附近时）
    async loadMoreOnSwipeDown() {
        if (this.isLoading || this.postList.length === 0) {
            return;
        }

        this.isLoading = true;

        try {
            // 获取当前列表第一条数据的id
            const firstPostId = this.postList[0].id;

            const request = new PostRequest.QueryList();
            request.uid = this.request.uid;
            request.type = this.request.type; // 保持当前的类型
            request.postId = firstPostId;
            request.lnkId = this.postList[0].lnkId; // 保持当前的lnkId
            request.pageIndex = 1;
            request.pageSize = 10;
            request.operate = PagingOperate.DOWN; // DOWN获取新数据

            LoggerUtil.info("下滑加载数据，postId: {}, operate: DOWN", firstPostId);

            const result = await PostService.queryUserList(request);

            if (result && result.length > 0) {

                // 调整当前索引，避免跳跃
                const currentPostId = this.postList[this.currentIndex].id;


                result.forEach((post: PostInfo) => {
                    post.hideTitle = true;
                    // 确保新加载的数据也有正确的 postCurrent 初始值
                    if (post.postCurrent === undefined || post.postCurrent === null) {
                        post.postCurrent = 0;
                    }
                });

                // 添加到列表顶部
                this.postList.unshift(...result);

                // 更新postMap
                result.forEach((post: PostInfo) => {
                    this.postMap.set(post.id, post);
                });

                // 重新计算当前索引
                const newIndex = this.postList.findIndex(
                    (post) => post.id === currentPostId
                );
                if (newIndex !== -1) {
                    LoggerUtil.info("下滑加载后，索引从 {} 调整为 {}", this.currentIndex, newIndex);
                    this.currentIndex = newIndex;
                } else {
                    LoggerUtil.error("下滑加载后，未找到当前帖子ID: {}", currentPostId);
                }

                LoggerUtil.info(
                    "下滑加载了{}条新数据，当前索引调整为{}",
                    result.length,
                    this.currentIndex
                );
            }
        } finally {
            this.isLoading = false;
        }
    }

    // 上滑加载更多数据（在底部附近时）
    async loadMoreOnSwipeUp() {
        if (this.isLoading || this.postList.length === 0) {
            return;
        }

        this.isLoading = true;

        try {
            // 获取当前列表最后一条数据的id
            const lastPostId = this.postList[this.postList.length - 1].id;

            const request = new PostRequest.QueryList();
            request.uid = this.request.uid;
            request.type = this.request.type;
            request.postId = lastPostId;
            request.lnkId = this.postList[this.postList.length - 1].lnkId; // 保持当前的lnkId
            request.pageIndex = 1;
            request.pageSize = 10;
            request.operate = PagingOperate.UP; // UP获取老数据

            LoggerUtil.info("上滑加载数据，postId: {}, operate: UP", lastPostId);

            const result = await PostService.queryUserList(request);

            if (result && result.length > 0) {
                // 确保新加载的数据也有正确的 postCurrent 初始值
                result.forEach((post: PostInfo) => {
                    if (post.postCurrent === undefined || post.postCurrent === null) {
                        post.postCurrent = 0;
                    }
                });

                // 添加到列表底部
                Util.copyList(this.postList, result, PostInfo);

                // 更新postMap
                result.forEach((post: PostInfo) => {
                    this.postMap.set(post.id, post);
                });

                LoggerUtil.info("上滑加载了{}条历史数据", result.length);
            }
        } catch (error) {
            LoggerUtil.error("上滑加载数据失败", error);
        } finally {
            this.isLoading = false;
        }
    }

    changeShowTitle(e: any) {
        let id = e.currentTarget.dataset.id;
        const post = this.postMap.get(id);
        if (post) {
            post.hideTitle = !post.hideTitle;
        }
    }

    toUser(e: any) {
        const uid = e.currentTarget.dataset.id;
        uni.navigateTo({
            url: "/pages/blogger/blogger",
            success: (res) => {
                res.eventChannel.emit("toUser", { userId: uid });
            },
        });
    }
    onStopMove() { }

    onUnload() {
        if (this.observer) {
            this.observer.disconnect();
        }
    }

    generateId(itemId: any, index: any) {
        return itemId + Date.now();
    }

    initIntersectionObserver() { }
    truncate(str: string) {
        return Util.truncate(str, 10);
    }

    // 防抖版本的点赞方法
    async likePost(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let postId = e.currentTarget.dataset.id;
        let post = this.postMap.get(postId);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        if (post.liked) {
            await PostService.unlikePost(postId);
            post.liked = false;
            post.likeCount -= 1;
        } else {
            await PostService.likePost(postId);
            post.liked = true;
            post.likeCount += 1;
        }
    }

    // 防抖版本的收藏方法
    async collectPost(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let postId = e.currentTarget.dataset.id;
        let post = this.postMap.get(postId);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        if (post.collected) {
            await PostService.uncollectPost(postId);
            post.collected = false;
        } else {
            await PostService.collectPost(postId);
            post.collected = true;
        }
    }

    formatNumber(number: number): string {
        return Util.formatNumber(number);
    }

    //下载当前帖子的图片（带选择提示）
    async downPostWithChoice(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        let id = e.currentTarget.dataset.id;
        let post = this.postMap.get(id);
        if (Util.isEmpty(post) || !post) {
            LoggerUtil.error("post is null");
            return;
        }

        let urls = <any>[];
        // urls 是数组，直接遍历处理
        (post.urls as any).forEach((url: string, index: number) => {
            // 检查URL是否已经是完整的HTTP/HTTPS地址
            if (url.startsWith('http://') || url.startsWith('https://')) {
                urls.push(url);
            } else {
                urls.push(this.cdnHost + url);
            }
        });

        if (urls && urls.length > 0) {
            // 让用户选择操作方式
            uni.showActionSheet({
                itemList: ['预览保存(长按图片)', '全部保存', '逐张保存'],
                success: async (res) => {
                    if (res.tapIndex === 0) {
                        // 预览图片（用户可以长按保存）
                        await BatchDownloadUtil.previewImages(urls, post.postCurrent || 0);
                    } else if (res.tapIndex === 1) {
                        // 一次性保存全部
                        await BatchDownloadUtil.batchDownload(urls, 3);
                    } else if (res.tapIndex === 2) {
                        // 逐张保存，减少弹窗频率
                        await BatchDownloadUtil.batchDownload([urls[post.postCurrent]], 1);
                    }
                }
            });
        } else {
            UniUtil.showError({ title: "没有可下载的图片" });
        }
    }

    @Hook("onShareAppMessage")
    onShareAppMessage(e: any) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }

        let user = UserService.getUser();
        LoggerUtil.info("获取到用户信息:{}", JSON.stringify(user));
        let uid = Util.isEmpty(user) ? 0 : user.uid;
        let post = <any>this.postMap.get(e.target.dataset.id);

        return UniUtil.onShareAppMessage(
            post.title,
            post.title,
            "/pages/blogger/post?fromUid=" +
            uid +
            "&uid=" +
            user.uid +
            "&postId=" +
            post?.id,
            this.cdnHost + post?.urls[post.postCurrent]
        );
    }

    async loadInitialDataAroundTarget() {
        LoggerUtil.info(
            "开始加载目标帖子周围的数据，目标ID: {}",
            this.request.postId
        );

        const allPosts: PostInfo[] = [];

        // 1. 首先尝试加载目标帖子及其上方的新数据（检查是否为最新作品）
        const newerRequest = new PostRequest.QueryList();
        newerRequest.uid = this.request.uid;
        newerRequest.postId = this.request.postId;
        newerRequest.lnkId = this.request.lnkId; // 保持当前的lnkId
        newerRequest.type = this.request.type; // 保持当前的类型
        newerRequest.pageIndex = 1;
        newerRequest.pageSize = 5; // 先加载5条新数据检查
        newerRequest.operate = PagingOperate.DOWN; // DOWN获取新数据，id大于目标帖子id
        const newerPosts = await PostService.queryUserList(newerRequest);

        allPosts.push(...newerPosts);

        const olderRequest = new PostRequest.QueryList();
        olderRequest.uid = this.request.uid;
        olderRequest.postId = this.request.postId + 1;
        olderRequest.lnkId = this.request.lnkId + 1; // 保持当前的lnkId
        olderRequest.type = this.request.type; // 保持当前的类型
        olderRequest.pageIndex = 1;
        olderRequest.pageSize = 5; // 加载15条历史数据
        olderRequest.operate = PagingOperate.UP; // UP获取包含目标帖子及其之前的数据（id小于等于目标id）

        const olderPosts = await PostService.queryUserList(olderRequest);
        allPosts.push(...olderPosts);
        Util.copyList(this.postList, allPosts, PostInfo);
    }

    // scrollToTargetPost方法已不再需要，swiper使用currentIndex直接定位

    getDisplayText(text: string) {
        if (Util.isEmpty(text)) {
            return;
        }
        text = text.replace(/\n\n/g, '<br/>');
        return text;
    }

    copyTitle(item: PostInfo) {
        let login = UserService.checkAuth();
        if (!login) {
            return;
        }
        if (!item.title && !item.content) return;

        let words = item.title + '\n' + item.content;
        // 将<br/>替换为换行符
        words = words.replace(/<br\/?>/g, '\n\n');
        uni.setClipboardData({
            data: words,
            success: () => {
                uni.showToast({ title: '已复制', icon: 'none' });
            }
        });
    }

    onHide() { }
}